package k3.net.local
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.IPVersion;
	import flash.net.InterfaceAddress;
	import flash.net.NetworkInfo;
	import flash.net.NetworkInterface;
	
	import k3.event.KEvent;
	
	public final class GetLocalIpAdress extends EventDispatcher
	{
		public const NETWORK_NORMAL:String = "NETWORK_NORMAL";
		public const NETWORK_ABNORMAL:String = "NETWORK_ABNORMAL";
		public const IP_GET:String = "IP_GET";
		private var netWorkAnalyzer:NetWorkAnalyzer;
		private var networkcardInfo:Vector.<NetworkInterface>;
		private var netWorkStr:String="";
		private var ipAdd:String=""; 
		public function GetLocalIpAdress(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function check():void
		{
			getNetWorkInfo();
		}
		
		private function getNetWorkInfo():void
		{
			
			networkcardInfo=NetworkInfo.networkInfo.findInterfaces();
			
			if(!netWorkAnalyzer)
			{
				netWorkAnalyzer=new NetWorkAnalyzer();
				
				netWorkAnalyzer.addEventListener(netWorkAnalyzer.NETWORK_ABNORMAL,handleNetWorkAnalyzEnd);
				netWorkAnalyzer.addEventListener(netWorkAnalyzer.NETWORK_NORMAL,handleNetWorkAnalyzEnd);
				
			}
			
			netWorkAnalyzer.analyze(networkcardInfo);
		}
		
		private function handleNetWorkAnalyzEnd(e:KEvent):void
		{
			
			switch(e.type)
			{
				case netWorkAnalyzer.NETWORK_ABNORMAL:
					trace("网络问题");
					this.dispatchEvent(new KEvent(NETWORK_ABNORMAL,"网络问题 "+e.obj));
					break;
				case netWorkAnalyzer.NETWORK_NORMAL:
					trace("网络ok");
					this.dispatchEvent(new KEvent(NETWORK_NORMAL,"网络ok "));
					netWorkStr=e.obj;
					getIpAddress();
					break;
			}
		}
		
		private function getIpAddress():void
		{
			var index:int=netWorkStr.lastIndexOf(":");
			if(index!=-1)
			{
				this.ipAdd=netWorkStr.slice(index+1,netWorkStr.length);
				this.dispatchEvent(new KEvent(IP_GET,ipAdd));
			}
			
		}
		
	}
}